package com.scau402.system1.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class IdGenerator {

    private static final long START_TIME = 1704067200;//2024/1/1
    private StringRedisTemplate stringRedisTemplate;

    public IdGenerator(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix){
        LocalDateTime now = LocalDateTime.now();
        long timestamp = now.toEpochSecond(ZoneOffset.UTC) - START_TIME;
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        return timestamp << 8 | count;
    }

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.of(2024,1,1,0,0,0);
        System.out.println(now.toEpochSecond(ZoneOffset.UTC));
    }
}
